package jake2.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

public class Uncompressor {
	
	public static void main(String[] args) throws ZipException, IOException {
		System.out.println( "Uncompressing " + Downloader.Q2_EXE_FILE_NAME);
		new Uncompressor().uncompress( );
	}
	
	public void uncompress( ) throws ZipException, IOException {
		ZipFile zipFile = new ZipFile( new File( Downloader.Q2_EXE_FILE_NAME ) );
		
		Enumeration e = zipFile.entries();
		while (e.hasMoreElements()) {
			ZipEntry entry = (ZipEntry)e.nextElement();
			String name = entry.getName();
			int i;
			if ((i = name.indexOf("/baseq2")) > -1 && name.indexOf(".dll") == -1) {
				File outFile = new File("raw", name.substring(i));
				if (entry.isDirectory()) {
					outFile.mkdirs();
				} else {
					System.out.println("installing " + name.substring(i));
					outFile.getParentFile().mkdirs();
					
					OutputStream os = new FileOutputStream(outFile);
					InputStream is = zipFile.getInputStream(entry);
					byte[] buffer = new byte[ is.available() ];
					is.read( buffer );
					os.write( buffer );					
				}
			}
		}
	}
}
